var util = require('../../utils/util.js');
var api = require('../../config/api.js');

var app = getApp();

Page({
  data: {
    shopInfo: null,
    type: 0,
    searchValue: '',
    purchaseTotal: {
      "checkedCount": 0,
      "herbId": 0
    },
    checkedAllStatus: true,
    purchaseList: [],
    page: 1,
    limit: 10,
    totalPages: 1,
    hasLogin: false,
    //已中标-供货数量确认
    quoteNumConfirmShow: false,
    highSearchShow: false,
    herbSelectedShow: false,
    herbSelectedValue: '',
    herbSelectedId: '',
  },
  init: function () {
    this.setData({
      purchaseTotal: {
        "checkedCount": 0,
        "herbId": 0
      },
      checkedAllStatus: true,
      purchaseList: [],
      page: 1,
      limit: 10,
      totalPages: 1
    });
  },
  switchTab: function (event) {
    let type = event.currentTarget.dataset.index;
    if (type == 0) {
      //返回总览时情况检索条件
      this.setData({
        searchValue: '',
      });
    }
    this.setData({
      purchaseTotal: {
        "checkedCount": 0,
        "herbId": 0
      },
      checkedAllStatus: true,
      purchaseList: [],
      type,
      page: 1,
      limit: 10,
      totalPages: 1,
      //（已中标货物数量确认逻辑应用）单个采购对象
      purchase: {},
    });
    wx.setStorageSync('purchase_type', type);
    this.getPurchaseList();
  },
  switchTabMore() {
    if (this.data.hasLogin) {
      wx.navigateTo({
        url: "/pages/ucenter/quote/quote"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  getPurchaseList(reachBottom = false) {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    console.log('11111111111111-----'+this.data.type)
    if (this.data.type == '0') {
      console.log('222222222222')
      util.request(api.WantBuyList, {
        page: that.data.page,
        limit: that.data.limit,
        searchValue: that.data.searchValue
      }).then(function (res) {
        console.log('3333333333',res)
        if (res.errno === undefined) {
          let purchaseList = res.map((t) => {
            let purchase = {
              ...t,
              herbImage: t.herbImage || '/static/images/herb_icon.png'
            };
            return purchase;
          });
          
          // console.log(purchaseList)
          //触底加载新数据并保留老数据
          if (reachBottom) {
            purchaseList = [...that.data.purchaseList, ...purchaseList]
          }
          that.setData({
            purchaseList: purchaseList,
            totalPages: that.data.page
          });
          console.log(purchaseList)
          wx.hideLoading();
        }
      }).finally(() => {
        wx.hideLoading();
      });
    } else {
      util.request(api.PurchaseList, {
        type: that.data.type,
        page: that.data.page,
        limit: that.data.limit,
        herbId: that.data.herbSelectedId,
        searchValue: that.data.searchValue
      }).then(function (res) {
        if (res.errno === 0) {
          let purchaseList = res.data.list.map(item => {
            item.publishDt = util.formatTime2(new Date(item.publishDt), "Y/M/D");
            item.herbListImage && (item.herbListImage01 = item.herbListImage.split(',')[0]);
            item.dueTime = parseInt((new Date(item.dueTime).getTime() - new Date().getTime()));
            item.minTime = 10 * 60;
            return item;
          });
          //触底加载新数据并保留老数据
          if (reachBottom) {
            purchaseList = [...that.data.purchaseList, ...purchaseList]
          }
          that.setData({
            purchaseList: purchaseList,
            totalPages: res.data.pages
          });

          if (that.data.type == 1) {
            that.setData({
              checkedAllStatus: that.isCheckedAll(),
              'purchaseTotal.checkedCount': that.getCheckedCount()
            });
          }
          wx.hideLoading();
        }
      }).finally(() => {
        wx.hideLoading();
      });
    }
  },
  getCheckedCount: function () {
    let checkedCount = 0;
    this.data.purchaseList.forEach(function (v) {
      if (v.checked === true) {
        checkedCount += 1;
      }
    });
    return checkedCount;
  },
  checkedAll: function () {
    let that = this;
    let checkedAllStatus = that.isCheckedAll();
    let tmpPurchaseData = this.data.purchaseList.map(function (v) {
      v.checked = !checkedAllStatus;
      return v;
    });

    that.setData({
      purchaseList: tmpPurchaseData,
      checkedAllStatus: that.isCheckedAll(),
      'purchaseTotal.checkedCount': that.getCheckedCount()
    });
  },
  isCheckedAll: function () {
    return this.data.purchaseList.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  doCheckedAll: function () {
    let checkedAll = this.isCheckedAll()
    this.setData({
      checkedAllStatus: this.isCheckedAll(),
      'purchaseTotal.checkedCount': that.getCheckedCount()
    });
  },
  checkedItem: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let that = this;
    // let purchaseIds = [];
    // purchaseIds.push(that.data.purchaseList[itemIndex].itemId);
    // console.log(purchaseIds)
    let tmpPurchaseData = this.data.purchaseList.map(function (element, index, array) {
      if (index == itemIndex) {
        element.checked = !element.checked;
      }
      return element;
    });

    that.setData({
      purchaseList: tmpPurchaseData,
      checkedAllStatus: that.isCheckedAll(),
      'purchaseTotal.checkedCount': that.getCheckedCount()
    });
  },
  onLoad: function (options) {
    console.log(options)
    if (options.type) {
      this.setData({
        type: options.type
      });
    }
  },
  onReady: function () {

  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.init();
    this.getPurchaseList();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onReachBottom() {
    if (this.data.totalPages > this.data.page) {
      this.setData({
        page: this.data.page + 1
      });
    } else {
      return false;
    }
    this.getPurchaseList(true);
  },
  onShow: function () {
    if (app.globalData.hasLogin) {
      let shopInfo = wx.getStorageSync('shopInfo');
      this.setData({
        shopInfo: shopInfo
      });

      let type = wx.getStorageSync('purchase_type') || this.data.type;
      this.setData({
        purchaseTotal: {
          "checkedCount": 0,
          "herbId": 0
        },
        checkedAllStatus: true,
        purchaseList: [],
        type: type, //切换成待报价
        page: 1,
        limit: 10,
        totalPages: 1
      });
      this.getPurchaseList();
    }
    this.setData({
      hasLogin: app.globalData.hasLogin
    });
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭
  },
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  goWaitingQuote(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    // console.log(purchase)

    // this.setData({
    //   herbSelectedId: herb.id,
    //   herbSelectedValue: `${herb.name} -- 规格/${herb.specifications} - 单位/${herb.unit}`
    // });
    this.setData({
      herbSelectedId: purchase.herbId,
      herbSelectedValue: `${purchase.herbName} -- 规格/${purchase.specifications} - 单位/${purchase.measurementUnit}`,

      searchValue: '',
      purchaseTotal: {
        "checkedCount": 0,
        "herbId": 0
      },
      checkedAllStatus: true,
      purchaseList: [],
      type: 1, //切换成待报价
      page: 1,
      limit: 10,
      totalPages: 1
    });
    this.getPurchaseList();
  },
  //采购明细
  openPurchase(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];

    wx.setStorageSync('purchasesStr', JSON.stringify([purchase]));
    wx.navigateTo({
      url: `/pages/purchaseDetail/purchaseDetail?id=${purchase.id}&itemId=${purchase.itemId}&index=${that.data.type}`
    });
  },
 
  //按下事件开始  
  touchStart: function (e) {
    let that = this;
    that.setData({
      touchStart: e.timeStamp
    })
  },
  //按下事件结束  
  touchEnd: function (e) {
    let that = this;
    that.setData({
      touchEnd: e.timeStamp
    })
  },
  onChange(e) {
    this.setData({
      searchValue: e.detail,
    });
  },
  onSearch() {
    this.getPurchaseList();
  },
  addPurchase() {
    wx.navigateTo({
      url: '/pages/purchaseAdd/purchaseAdd'
    })
  },
  quote(event) {
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    wx.setStorageSync('purchaseListStr', JSON.stringify([purchase]));
    wx.navigateTo({
      url: `/pages/quote/quote`
    })
  },
  quoteAll() {
    if (this.data.purchaseTotal.checkedCount <= 0) {
      wx.showModal({
        title: '提示信息',
        content: '请勾选要报价的药材',
        showCancel: false
      });
      return false;
    }
    let quoteList = this.data.purchaseList.filter((t) => t.checked === true);
    let herbId = quoteList[0].herbId;
    let checkHerb = quoteList.find((t) => t.herbId != herbId);
    if (checkHerb) {
      wx.showModal({
        title: '提示信息',
        content: '请选择同一种药材再报价',
        showCancel: false
      });
      return false;
    }
    wx.setStorageSync('purchaseListStr', JSON.stringify(quoteList));
    wx.navigateTo({
      url: `/pages/quote/quote`
    })
  },
  //已中标-报价数量确认
  quoteNum(event) {
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    // console.log(purchase)
    this.setData({
      quoteNumConfirmShow: true,
      purchase: purchase
    });
  },
  bindinputReceivedAmount(event) {
    let purchase = this.data.purchase;
    purchase.receivedAmount = this.money(event.detail);
    this.setData({
      purchase: purchase
    });
  },
  quoteNumConfirm() {
    let purchase = this.data.purchase;
    // console.log(purchase)

    if (purchase.receivedAmount <= 0) {
      util.showErrorToast('请输入数量');
      return false;
    }

    let that = this;
    wx.showModal({
      title: '',
      content: '确定修改吗？',
      success: function (res) {
        if (res.confirm) {
          util.request(api.PurchaseAmountUpdate, {
            ...purchase
          }, 'POST').then(function (res) {
            if (res.errno === 0) {
              that.onQuoteNumConfirmClose();
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 2000
              });
            } else {
              util.showErrorToast(res.errmsg);
            }
          });
        }
      }
    })
  },
  onQuoteNumConfirmClose() {
    this.setData({
      quoteNumConfirmShow: false
    });
  },
  /**
   * @method: 金额输入限制
   * @params: val接收number值
   */
  money(val) {
    let num = val.toString(); //先转换成字符串类型
    if (num.indexOf('.') == 0) { //第一位就是 .
      num = '0' + num
    }
    num = num.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (num.indexOf(".") < 0 && num != "") {
      num = parseFloat(num);
    }
    return num
  },
  //高级检索逻辑
  onHighSearch() {
    this.setData({
      highSearchShow: true
    });
  },
  onHighSearchClose() {
    this.setData({
      highSearchShow: false
    });
  },
  //执行高级检索
  highSearch() {
    this.getPurchaseList();
  },
  onHerbSelectClear() {
    this.setData({
      herbSelectedId: '',
      herbSelectedValue: ''
    });
    this.highSearch();
  },
  //药材选择回调方法
  herbSelected(e) {
    // console.log('herbSelected',e.detail)
    let herb = e.detail;
    this.setData({
      herbSelectedId: herb.id,
      herbSelectedValue: `${herb.name} -- 规格/${herb.specifications} - 单位/${herb.unit}`
    });
    this.highSearch();
  },
  addbuy(){
    wx.navigateTo({
      url: "/pages/addWantBuy/addWantBuy"
    });
  },
})